$(function () {
    chinese.sSearch = "用户名搜索";
    var table = $('#userList').DataTable({
        "processing": true,
        "serverSide": true,
        "bSort": false,
        "ajax": {
            "url": "user/getData",
            "data": function (d) {
                d.loginNameQuery = d.search.value;
            }
        },
        "aoColumnDefs": [{
                "targets": 0,
                "bSortable": false,
                "searchable": false,
                "className": "text-center",
                "mRender": function (data, type, row) {
                    return '<input type="checkbox" />';
                }
            }, {
                "targets": 1,
                "mRender": function (data, type, row) {
                    return '<a href="user/index/' + row.user.id + '" target="_blank">' + row.user.loginName + '</a>';
                }
            }, {
                "targets": 2,
                "mRender": function (data, type, row) {
                    return row.user.mobile;
                }
            }, {
                "targets": 3,
                "mRender": function (data, type, row) {
                    return row.user.name ? row.user.name : '-';
                }
            }, {
                "targets": 4,
                "mRender": function (data, type, row) {
                    return row.user.idNumber ? row.user.idNumber : '-';
                }
            }, {
                "targets": 5,
                "searchable": false,
                "mRender": function (data, type, row) {
                    var status = row.account
                        ? row.account.usrCustId
                        : '未开通';
                    return status;
                }
            }, {
                "targets": 6,
                "searchable": false,
                "mRender": function (data, type, row) {
                    return $.number(row.fund.available, 2);
                }
            }, {
                "targets": 7,
                "searchable": false,
                "mRender": function (data, type, row) {
                    var status = row.user.enabled
                        ? '<i class="fa fa-check text-success"></i>正常'
                        : '<i class="fa fa-lock text-danger mr4"></i>冻结';
                    return status;
                }
            }, {
                "targets": 8,
                "searchable": false,
                "visible": false,
                "mRender": function (data, type, row) {
                    return $.format.date(new Date(row.user.registerTime), "yyyy/MM/dd HH:mm");
                }
            }, {
                "targets": 9,
                "searchable": false,
                "bSortable": false,
                "visible": false,
                "mRender": function (data, type, row) {
                    return row.user.lastLoginTime !== null
                        ? $.format.date(new Date(row.user.lastLoginTime), "yyyy/MM/dd HH:mm")
                        : '-';
                }
            }, {
                "targets": 10,
                "searchable": false,
                "bSortable": false,
                "visible": false,
                "mRender": function (data, type, row) {
                    return row.referee !== null
                        ? '<a href="user/index/' + row.referee.id + '" target="_blank">' + row.referee.loginName + '</a>'
                        : '-';
                }
            }, {
                "targets": -1,
                "bSortable": false,
                "searchable": false,
                "mRender": function (data, type, row) {
                    var operations = $("#operationHTML").html().replace(/#id/g, row.user.id).replace(/#loginName/g, row.user.loginName);
                    if (!row.user.enabled) {
                        operations = operations.replace("glyphicons-lock", "glyphicons-unlock").replace("冻结", "激活");
                    }
                    return operations;
                }
            }],
        "order": [[8, "desc"]],
        "oLanguage": chinese,
        "iDisplayLength": 10,
        "aLengthMenu": [
            [10, 25, 50, -1],
            [10, 25, 50, "全部"]
        ],
        "sDom": '<"dt-panelmenu clearfix"l<"pull-right"Tf>r>t<"dt-panelfooter clearfix"ip>',
        "oTableTools": {
            "aButtons": [{
                    "sExtends": "copy",
                    "sButtonText": "复制",
                    "fnComplete": function (nButton, oConfig, oFlash, sFlash) {
                        alert('列表内容已复制到剪贴板');
                    }
                }, {
                    "sExtends": "xls",
                    "sButtonText": "导出为Excel"
                }
            ],
            "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
        },
        "fnDrawCallback": function () {
            // 高亮显示搜索内容
            if ($("#userList_filter input").val() !== "") {
                $("#userList").highlight($("#userList_filter input").val());
            }
        }
    });

    // 选中/取消选择行
    $("#userList tbody").on("click", 'input[type=checkbox]', function (e) {
        e.stopPropagation();
        if ($(this).prop("checked")) {
            $(this).parents("tr").addClass("selected");
        } else {
            $(this).parents("tr").removeClass("selected");
        }
    });
    /**
     * 显示/隐藏列
     */
    $('label.toggle-label input[type=checkbox]').on('change', function (e) {
        var checked = $(this).prop("checked"),
            col_index = $(this).attr('data-column'),
            column = table.column(col_index);

        if (checked) {
            column.visible(true);
        } else {
            column.visible(false);
        }
    });

    // 选中全部行
    function selectAllRows(selectAll) {
        if (selectAll) {
            $('#userList tbody tr').removeClass("selected");
            $('#userList tbody tr').addClass("selected");
            $('#userList tbody input[type=checkbox]').prop("checked", true);
        } else {
            $('#userList tbody tr').removeClass("selected");
            $('#userList tbody input[type=checkbox]').prop("checked", false);
        }
    }

    /**
     * 用户重置密码
     */
    $("#userList").on("click", ".reset-pwd-btn", function (e) {
        e.preventDefault();
        e.stopPropagation();
        if (confirm("确定重置该用户登录密码？")) {
            var uid = $(this).data("id");
            $.get("user/resetPassword/" + uid, function (res) {
                if (res.success) {
                    alert("用户密码已重置！新的随机密码已通过短信通知用户");
                } else {
                    alert("用户密码重置失败");
                }
            }).fail(function () {
                alert("网络通信错误");
            });
        }
    });
});

/**
 * 更改用户账号状态
 * @param {type} userId
 * @returns {undefined}
 */
function changeStatus(userId) {
    if (confirm('确定要更新用户状态？')) {
        $.get("user/changeStatus/" + userId, function (res) {
            if (res.success) {
                alert("用户状态更新成功");
                location.reload();
            } else {
                alert("用户状态更新失败");
            }
        });
    }
}

/**
 * 更改用户账号状态
 * @param {type} userId
 * @returns {undefined}
 */
function refreshLogin(userId) {
    if (confirm('确定要刷新用户登录状态？')) {
        $.get("user/refreshLogin/" + userId, function (res) {
            if (res.success) {
                alert(res.message);
                location.reload();
            } else {
                alert("用户状态刷新失败");
            }
        });
    }
}